<?php

use Fox\Html\Interval;
use Fox\Html\DropList\Radio;
use Fox\SalesDistribution\Sales\Partner\Role;
use Fox\Grid\FieldCat\Field;
use Doctrine\DBAL\Types\Type;
use Fox\SalesDistribution\Sales\Inquiry;
use Fox\SalesDistribution\Sales\Inquiry\Status;
$xview = Xview::instance();

$screen = new Fox\Html\Screen("eSelect","execute");
$block = new Fox\Html\Block("gCriteria",Msg(Fox::MSGCL,29));
$block->add(new Interval("period",true,mktime(0,0,0,1,1,date("Y")),time()));
$block->add(new Radio("output_type",true,true,1))->addAllOption();
$screen->add($block);
if($screen->submitted())
{
	$inputs = $screen->get();
	if(!$screen->errors())
	{
		$legends = $tickLabels = null;
		$grid = new Fox\Grid();
		$grid->fieldcat(array("status"));
		$grid->fieldcat()->field("status")
						->fixed(true)
						->width(40)
						->setNoWrap()
						->SetClass("separator-right");
		$grid->setXlsDownload();
		$formatInterval = "P1M";
		$formatType = "m/y";

		$startDate = new DateTime($inputs['period_left']);
		$endDate = new DateTime($inputs['period_right']);

		// Build Grid Columns
		while($startDate <= $endDate)
		{
			$fieldName1 = "amount-".$startDate->format($formatType);
			$inquiryOfTheMonth[$startDate->format($formatType)] = 0;
			$field = new Field("amount",$fieldName1);

			$field->align("right");
			$grid->fieldcat()->add($field);
			$fieldName2 = "rate-".$startDate->format($formatType);
			$field = new Field("rate",$fieldName2);
			$field->dataType("rate");
			$field->align("right");
			$field->SetClass("separator-dashed-left separator-right");
			$grid->fieldcat()->add($field);

			$groupingField = new Field(array("month","month_".$startDate->format($formatType)));
			$groupingField->setClass("gd-col-group separator-left")->label($startDate->format($formatType));
			$grid->fieldcat()->buildSubTitleByGrouping(array($fieldName1,$fieldName2), $groupingField);
			// Ticks Label for graphs
			$tickLabels .= "&tickLabels[]=".urlencode($startDate->format($formatType));
			$startDate->add(new DateInterval($formatInterval));
		}
		$grid->fieldcat()->add(new Field("cssclass"));
		$grid->fieldcat()->field("cssclass")->noOutput();
		$grid->fieldcat()->setClassField("cssclass");
		$grid->layout()->scrollHorizontal();
		$finder = new Status();
		$status = $finder->find(new Fox\Dao\SqlFragment("statusid != ?",array(1)));
		foreach($status as $item)
		{
			$data[$item->getId()] = $grid->GetEmptyLine(array("status" => $item->label()));
			$statusId[$item->getId()] = $item->getId();
			$linePlot[$item->getId()] = array();
			$legends .= "&legends[]=".urlencode($item->label());

		}

		// Additionnal Lines
		$data["total"] = $grid->GetEmptyLine(array("status" => "Total","cssclass" => "xv-grid-total"));
		$data["month"] = $grid->GetEmptyLine(array("status" => "Offre du Mois"));
		$data["month_avg"] = $grid->GetEmptyLine(array("status" => "Moyenne Mensuelle"));
		$data["month_rate"] = $grid->GetEmptyLine(array("status" => "Offres du mois/moyenne"));
		$data["success_rate"] = $grid->GetEmptyLine(array("status" => "Tx de r&eacute;ussite"));

		$startDate = new DateTime($inputs['period_left']);
		// Load Data
		$query = \Fox\Dao::infos(Inquiry::className())->handle()->createQueryBuilder();
		$query->select('status','start_date','total1','total2')
				->from('inquiries','t')
				->innerJoin('t', 'inquiry_partners', 'pa','t.inquiryid = pa.inquiryid');
		$fragments[] = new Fox\Dao\SqlFragment("start_date >= ? AND start_date <= ? ",
											array($startDate,$endDate),
											array(Type::DATE,Type::DATE));

		$fragments[] = new Fox\Dao\SqlFragment("t.loekz = ? AND pa.role = ?",array(0,Role::RESPONSIBLE_AGENCY));
		if(!Fox\Authorization\Manager::check(User::AUTH_VIEW_ALL))
			$fragments[] = User::current()->inquiryFragments();
		$fragment = Fox\Dao\SqlFragment::combine($fragments);
		$result = $fragment->pushIn($query)->execute()->fetchAll(PDO::FETCH_ASSOC);
		foreach($result as $item)
		{
			$date = new DateTime($item['start_date']);
			$fieldName = $date->format($formatType);
			$statuid = $item['status'];
			/*
			if($item['amount'] > 0)
				$amount = $item['amount'];
			else
			*/
			$amount = $item['total1'];
			$data[$statuid]["amount-$fieldName"] += $amount;

			$startDate->sub(new DateInterval($formatInterval));
			{

			}
			$data["month"]["amount-$fieldName"] += $amount;
			$data["total"]["amount-$fieldName"] += $amount;
			$inquiryOfTheMonth[$fieldName] += 1;
		}
		// Move amount to be year to date
		$statusId["total"] = "total";
		foreach($statusId as $statuid => $value)
		{
			$first = true;
			$startDate = new DateTime($inputs['period_left']);
			$monthNb = 1;
			while($startDate < $endDate)
			{
				$amountFieldName = "amount-".$startDate->format($formatType);
				if($first)
				{
					$first = false;
					$last_amount = $data[$statuid][$amountFieldName];
					if($statuid == "total")
					{
						$data["month_avg"][$amountFieldName] = $last_amount;
					}
				}
				$startDate->add(new DateInterval($formatInterval));
				$amountFieldName = "amount-".$startDate->format($formatType);
				if(isset($data[$statuid][$amountFieldName]))
				{
					$data[$statuid][$amountFieldName] += $last_amount;
					$last_amount = $data[$statuid][$amountFieldName];
					$monthNb++;
					if($statuid == "total")
					{
						$data["month_avg"][$amountFieldName] = $data["total"][$amountFieldName] / $monthNb;
					}
				}
			}
		}
		// Building Rate
		foreach($statusId as $statuid => $value)
		{
			$startDate = new DateTime($inputs['period_left']);
			while($startDate <= $endDate)
			{
				$dateFieldName = $startDate->format($formatType);
				$total = $data["total"]["amount-$dateFieldName"];
				$startDate->add(new DateInterval($formatInterval));

				if($total > 0)
				{
					$data[$statuid]["rate-$dateFieldName"] =  round($data[$statuid]["amount-$dateFieldName"] / $total * 100,2);
					if($statuid == "total")
					{
						$data["success_rate"]["amount-$dateFieldName"] = round($data[Inquiry::STATUS_WIN]["rate-$dateFieldName"]);
						$graphData1[] = $data["success_rate"]["amount-$dateFieldName"];

						$data["success_rate"]["amount-$dateFieldName"] .="%";
						$data["month_rate"]["amount-$dateFieldName"] = round($data["month"]["amount-$dateFieldName"] /$total * 100,2) ;

						$data["month_rate"]["amount-$dateFieldName"] .="%";
					}
					if(isset($linePlot[$statuid]))
					{
						$linePlot[$statuid][] = round($data[$statuid]["rate-$dateFieldName"],2);
					}
				}
				else
				{
					if(isset($linePlot[$statuid]))
					{
						$linePlot[$statuid][] = 0;
					}
				}

			}
		}
		$output = null;
		if($inputs['output_type'] == 1 || $inputs['output_type'] == Radio::ALL)
		{
			$grid->setDatas($data);
			$output .= $grid->Display();
		}
		if($inputs['output_type'] == 0 || $inputs['output_type'] == Radio::ALL)
		{
			$static = "?mod=charts&act=lineplot&xvtrs=none";
			// Colors
			$colors  = "&colors[]=".urlencode("#3366cc");
			$colors .= "&colors[]=".urlencode("#109618");
			$colors .= "&colors[]=".urlencode("#dc3912");
			$colors .= "&colors[]=".urlencode("#fd9800");

			$graphData1 = json_encode($graphData1);
			foreach($inquiryOfTheMonth as $value)
			{
				$graphData2[] = $value;
			}
			$graphData2 = json_encode($graphData2);
			$output .= "<div>";
			$title = urlencode("Taux de r&eacute;ussite");
			$output .= "<img style=\"padding:5px 5px\" src=\"$static&$tickLabels&data=$graphData1&title=$title\" >";
			$title = urlencode("Offres par mois");
			$output .= "<img style=\"padding:5px 5px\" src=\"$static&$tickLabels&data=$graphData2&title=$title\" >";
			$title = urlencode("Proportion des offres &eacute;mises");
			$graphData3 = urlencode(json_encode($linePlot));
			$output .= "<img style=\"padding:5px 5px\" src=\"$static&tickmark=false&$colors&$tickLabels&$legends&multiple=true&data=$graphData3&title=$title\" >";
			$output .= "</div>";
		}

	}
}
echo '<h1>'.$xview->pageTitle().'</h1>';
echo $screen->Display();
if(isset($output))
	echo $output;